<template>
  <!-- 组织生活 -->
  <base-breadcrumb class="orgLife-container">
    <searchData
      :search-data="searchArr"
      @search="handleSearch"
    />
    <a-card :bordered="false">
      <!-- <title-name title="组织生活列表" /> -->
      <div class="pub-table-action-btn">
        <a-button
          v-btnPermission="'pa_008_add_01'"
          type="primary"
          @click="handleUpdate({}, 'add')"
        >
          新增
        </a-button>
      </div>
      <div class="mb10">
        <a-collapse
          v-model="activeKey"
          :bordered="false"
          expand-icon-position="right"
          @change="handleExpand"
        >
          <a-collapse-panel
            style="background: #e6f3fc; border: none"
            :show-arrow="false"
          >
            <template v-slot:header>
              <a-row
                type="flex"
                justify="space-between"
                align="middle"
                style="width: 100%"
              >
                <div>
                  <a-icon
                    type="info-circle"
                    theme="twoTone"
                  />
                  <span>
                    共计：
                    <a>{{ totalInfo.totalNum || 0 }} 个</a>
                  </span>
                </div>
                <a class="btn_right">
                  <span>汇总详情</span>
                  <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                </a>
              </a-row>
            </template>
            <div class="panel-header">
              <div class="select-wrapper">
                <span>会议季度：</span>
                <a-select
                  v-model="selectQuarter"
                  style="width: 200px"
                >
                  <a-select-option
                    v-for="item in quarterList"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </div>
              <a-button
                class="ml20"
                type="primary"
                @click="handleConfirmTotal"
              >
                确定汇总
              </a-button>
            </div>
            <div class="panel-body">
              <a-row :gutter="10">
                <a-col :span="6">
                  <TreePartyOrg
                    ref="treePartyOrg"
                    :selected-keys.sync="selectedKeys"
                    :show-child-with-search="true"
                    :org-status="1"
                    @loader="getTable"
                  />
                </a-col>
                <a-col :span="18">
                  <s-table
                    ref="totalTable"
                    row-key="id"
                    :columns="totalColumns"
                    :data="loadTotalData"
                    show-size-changer
                    show-quick-jumper
                    show-pagination="auto"
                  >
                    <template
                      v-for="(item, index) in totalColumns"
                      :slot="item.dataIndex"
                      slot-scope="text"
                    >
                      <span
                        v-if="!!text"
                        :key="index"
                      >已完成</span>
                      <span
                        v-else
                        :key="index"
                        style="color: red"
                      >未完成</span>
                    </template>
                  </s-table>
                </a-col>
              </a-row>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </div>
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
      >
        <template
          slot="lifeLevel"
          slot-scope="text, record"
        >
          {{ filterLevel(text) }}
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-btnPermission="'pa_008_loo_04'"
              @click="handleUpdate(record, 'look')"
            >查看</a>
            <a
              v-btnPermission="'pa_008_edi_02'"
              @click="handleUpdate(record, 'edit')"
            >编辑</a>
            <a
              v-btnPermission="'pa_008_del_03'"
              @click="handleUpdate(record, 'delete')"
            >删除</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { getList, deleteData, getTotalList } from '@/api/partyMasses/partyManage/orgLife.js'
import { packageConfirm } from '@/utils/baseAction.js'
import { Collapse } from 'ant-design-vue'
import Selector from '@/components/Select/Selector.vue'
import TreePartyOrg from '@/components/businessComponents/TreePartyOrg'
import { PARTY_TYPE_MAP } from '@/config/businessConfig.js'

const searchArr = [
  {
    name: '组织生活名称',
    value: 'lifeName',
    type: 'input'
  },
  {
    name: '组织生活类型',
    valueKey: 'lifeTypeId',
    type: Selector,
    urlType: 'union',
    selectType: 26
  },
  {
    name: '组织生活级别',
    value: 'lifeLevel',
    type: 'select',
    data: [
      {
        label: '党委',
        value: 1
      },
      {
        label: '党总支',
        value: 2
      },
      {
        label: '党支部',
        value: 3
      }
    ]
  },
  {
    name: '举行组织名称',
    value: 'partyOrgName',
    type: 'input'
  },
  {
    name: '组织生活时间',
    value: 'lifeTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['lifeStartTime', 'lifeEndTime']
    }
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '组织生活名称',
    dataIndex: 'lifeName'
  },
  {
    title: '组织生活类型',
    dataIndex: 'lifeTypeName'
  },
  {
    title: '举办组织',
    dataIndex: 'partyOrgName',
    ellipsis: true
  },
  {
    title: '组织生活级别',
    dataIndex: 'lifeLevel',
    scopedSlots: { customRender: 'lifeLevel' }
  },
  {
    title: '主持人',
    dataIndex: 'presenter'
  },
  {
    title: '组织生活日期',
    dataIndex: 'lifeTime'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

const totalColumns = [
  {
    title: '党组织名称',
    dataIndex: 'partyOrgName'
  },
  {
    title: '支部委员会（本季度完成情况）',
    dataIndex: 'branchCommittee',
    scopedSlots: { customRender: 'branchCommittee' }
  },
  {
    title: '党员大会（本季度完成情况）',
    dataIndex: 'partyMemberConference',
    scopedSlots: { customRender: 'partyMemberConference' }
  },
  {
    title: '党小组大会（本季度完成情况）',
    dataIndex: 'partyConference',
    scopedSlots: { customRender: 'partyConference' }
  },
  {
    title: '党课（本季度完成情况）',
    dataIndex: 'partyLecture',
    scopedSlots: { customRender: 'partyLecture' }
  },
  {
    title: '主题党日（本季度完成情况）',
    dataIndex: 'thematicPartyDay',
    scopedSlots: { customRender: 'thematicPartyDay' }
  }
]
export default {
  name:'a'+ Date.now(),
  components: {
    STable,
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel'],
    TreePartyOrg,
  },
  data() {
    return {
      activeKey: [],
      selectedKeys: [],
      totalColumns: totalColumns,
      quarterList: [], // 季度下拉列表
      totalInfo: {
        totalNum: 0
      },
      searchArr,
      columns: columns,
      queryParam: {},
      selectQuarter: ''
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    filterLevel(val) {
      return PARTY_TYPE_MAP[val] || ''
    },
    handleConfirmTotal() {
      this.$refs.totalTable.refresh(true)
    },
    handleExpand(keys) {
      if (keys.length) {
        this.$nextTick(() => {
          this.$refs.treePartyOrg.getList().then(() => {
            this.handleConfirmTotal()
          })
        })
      }
    },
    loadTotalData(params) {
      const time = this.selectQuarter.split(',')
      return getTotalList({
        ...params,
        query: { partyOrgId: this.selectedKeys[0], quarterStartTime: time[0], quarterEndTime: time[1] }
      })
    },
    getTable() {
      this.$refs.totalTable.refresh(true)
    },
    initPage() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const valueMap = {
        一: ['01', '03'],
        二: ['03', '06'],
        三: ['06', '09'],
        四: ['09', '12']
      }
      const list = []
      // 生成前后十年的下拉数据，本年度则只生成最多当前季度+1的数据，默认选中当前季度
      for (let i = year - 10; i < year + 10; i++) {
        Object.keys(valueMap).forEach((item) => {
          const [startMonth, endMonth] = valueMap[item]
          if (i === year) {
            if (month >= Number(startMonth) && month <= Number(endMonth)) {
              this.selectQuarter = `${i}-${startMonth},${i}-${endMonth}`
            }
            if (month + 3 < Number(startMonth)) return
          }
          list.push({
            label: `${i}第${item}季度`,
            value: `${i}-${startMonth},${i}-${endMonth}`
          })
        })
      }
      this.quarterList = list
    },
    /**
     * 处理数据的相关操作（增删改查）
     */
    handleUpdate(data, pageType) {
      const commonHandler = () => {
        this.$router.push({
          path: '/partyMasses/partyManage/orgLife/update',
          query: {
            id: data.id || '',
            pageType: pageType
          }
        })
      }
      const actionMap = {
        add: commonHandler,
        edit: commonHandler,
        look: commonHandler,
        delete: async () => {
          packageConfirm({
            callback: async () => {
              await deleteData({ id: data.id })
              this.$message.success('删除成功')
              this.refreshTable()
            }
          })
        }
      }
      actionMap[pageType] && actionMap[pageType]()
    },
    handleSearch(val = {}) {
      this.queryParam = {
        ...val
      }
      this.refreshTable()
    },
    refreshTable() {
      this.$refs.table.refresh(true)
    },
    async loadData(parameter) {
      const requestParameters = Object.assign({}, { ...parameter }, { query: { ...this.queryParam } })
      return getList(requestParameters).then((res) => {
        this.totalInfo.totalNum = res.totalSize
        return {
          code:200,
          data: res.data,
          currentPage: res.currentPage,
          totalSize: res.totalSize
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.panel-header {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
}
.panel-body {
  background-color: #ffffff;
}
</style>